import { fetchUserCenter } from '../../services/usercenter/fetchUsercenter';
import { loginByWeixin, getUserProfileInfo } from '../../services/usercenter/login';
import Toast from 'tdesign-miniprogram/toast/index';

const menuData = [
  [
    {
      title: '收货地址',
      tit: '',
      url: '',
      type: 'address',
    },
    {
      title: '优惠券',
      tit: '',
      url: '',
      type: 'coupon',
    },
    {
      title: '积分',
      tit: '',
      url: '',
      type: 'point',
    },
  ],
  [
    {
      title: '帮助中心',
      tit: '',
      url: '',
      type: 'help-center',
    },
    {
      title: '客服热线',
      tit: '',
      url: '',
      type: 'service',
      icon: 'service',
    },
  ],
];

const orderTagInfos = [
  {
    title: '待付款',
    iconName: 'wallet',
    orderNum: 0,
    tabType: 5,
    status: 1,
  },
  {
    title: '待发货',
    iconName: 'deliver',
    orderNum: 0,
    tabType: 10,
    status: 1,
  },
  {
    title: '待收货',
    iconName: 'package',
    orderNum: 0,
    tabType: 40,
    status: 1,
  },
  {
    title: '待评价',
    iconName: 'comment',
    orderNum: 0,
    tabType: 60,
    status: 1,
  },
  {
    title: '退款/售后',
    iconName: 'exchang',
    orderNum: 0,
    tabType: 0,
    status: 1,
  },
];

const getDefaultData = () => ({
  showMakePhone: false,
  userInfo: {
    avatarUrl: '',
    nickName: '正在登录...',
    phoneNumber: '',
  },
  menuData,
  orderTagInfos,
  customerServiceInfo: {},
  currAuthStep: 1,
  showKefu: true,
  versionNo: '',
});

Page({
  data: getDefaultData(),

  onLoad() {
    this.getVersionInfo();
  },

  onShow() {
    this.getTabBar().init();
    this.init();
  },
  onPullDownRefresh() {
    this.init();
  },

  init() {
    this.fetUseriInfoHandle();
  },

  fetUseriInfoHandle() {
    const token = wx.getStorageSync('token');
    if (!token) {
      // 未登录
      this.setData({
        userInfo: {
          avatarUrl: '',
          nickName: '请登录',
          phoneNumber: '',
        },
        currAuthStep: 1,
      });
      wx.stopPullDownRefresh();
      return;
    }

    // 直接从数据库获取用户信息，而不是使用mock数据
    wx.request({
      url: 'http://localhost:8080/api/wx/profile',
      method: 'GET',
      header: {
        'Authorization': token,
        'content-type': 'application/json'
      },
      success: (res) => {
        if (res.statusCode === 200) {
          const userInfo = res.data;
          console.log('个人中心用户信息已从数据库获取:', userInfo);
          console.log('个人中心头像URL:', userInfo.avatarUrl);
          
          // 获取其他信息（使用原来的方式获取订单数据等）
          fetchUserCenter().then(({ countsData, orderTagInfos: orderInfo, customerServiceInfo }) => {
            // eslint-disable-next-line no-unused-expressions
            menuData?.[0].forEach((v) => {
              countsData.forEach((counts) => {
                if (counts.type === v.type) {
                  // eslint-disable-next-line no-param-reassign
                  v.tit = counts.num;
                }
              });
            });
            const info = orderTagInfos.map((v, index) => ({
              ...v,
              ...orderInfo[index],
            }));
            
            this.setData({
              userInfo: {
                ...userInfo,
                // 确保头像URL有效，如果为空则使用默认头像
                avatarUrl: userInfo.avatarUrl || 'https://tdesign.gtimg.com/miniprogram/template/retail/usercenter/icon-user-center-avatar@2x.png'
              },
              menuData,
              orderTagInfos: info,
              customerServiceInfo,
              currAuthStep: 2,
            });
            wx.stopPullDownRefresh();
          });
        } else {
          console.error('获取用户信息失败:', res.data);
          // 降级处理：使用原来的逻辑
          this.fallbackToOriginalLogic();
        }
      },
      fail: (err) => {
        console.error('获取用户信息网络错误:', err);
        // 降级处理：使用原来的逻辑
        this.fallbackToOriginalLogic();
      }
    });
  },

  // 降级处理方法
  fallbackToOriginalLogic() {
    fetchUserCenter().then(({ userInfo, countsData, orderTagInfos: orderInfo, customerServiceInfo }) => {
      // eslint-disable-next-line no-unused-expressions
      menuData?.[0].forEach((v) => {
        countsData.forEach((counts) => {
          if (counts.type === v.type) {
            // eslint-disable-next-line no-param-reassign
            v.tit = counts.num;
          }
        });
      });
      const info = orderTagInfos.map((v, index) => ({
        ...v,
        ...orderInfo[index],
      }));
      const mergedUser = userInfo || wx.getStorageSync('userInfo') || {};
      this.setData({
        userInfo: mergedUser,
        menuData,
        orderTagInfos: info,
        customerServiceInfo,
        currAuthStep: 2,
      });
      wx.stopPullDownRefresh();
    });
  },

  onClickCell({ currentTarget }) {
    const { type } = currentTarget.dataset;

    switch (type) {
      case 'address': {
        wx.navigateTo({ url: '/pages/address/address-list/index' });
        break;
      }
      case 'service': {
        this.openMakePhone();
        break;
      }
      case 'help-center': {
        Toast({
          context: this,
          selector: '#t-toast',
          message: '你点击了帮助中心',
          icon: '',
          duration: 1000,
        });
        break;
      }
      case 'point': {
        Toast({
          context: this,
          selector: '#t-toast',
          message: '你点击了积分菜单',
          icon: '',
          duration: 1000,
        });
        break;
      }
      case 'coupon': {
        wx.navigateTo({ url: '/pages/coupon/coupon-list/index' });
        break;
      }
      default: {
        Toast({
          context: this,
          selector: '#t-toast',
          message: '未知跳转',
          icon: '',
          duration: 1000,
        });
        break;
      }
    }
  },

  jumpNav(e) {
    const status = e.detail.tabType;

    if (status === 0) {
      wx.navigateTo({ url: '/pages/order/after-service-list/index' });
    } else {
      wx.navigateTo({ url: `/pages/order/order-list/index?status=${status}` });
    }
  },

  jumpAllOrder() {
    wx.navigateTo({ url: '/pages/order/order-list/index' });
  },

  openMakePhone() {
    this.setData({ showMakePhone: true });
  },

  closeMakePhone() {
    this.setData({ showMakePhone: false });
  },

  call() {
    wx.makePhoneCall({
      phoneNumber: this.data.customerServiceInfo.servicePhone,
    });
  },

  gotoUserEditPage() {
    const { currAuthStep } = this.data;
    if (currAuthStep === 2) {
      wx.navigateTo({ url: '/pages/user/person-info/index' });
      return;
    }
    // 未登录：跳转到登录页面
    wx.navigateTo({ url: '/pages/user/login/index' });
  },


  getVersionInfo() {
    const versionInfo = wx.getAccountInfoSync();
    const { version, envVersion = __wxConfig } = versionInfo.miniProgram;
    this.setData({
      versionNo: envVersion === 'release' ? version : envVersion,
    });
  },
});
